package com.xxchat.websocket;

import com.alibaba.fastjson.JSON;
import com.xxchat.entity.dto.MessageSendDTO;
import com.xxchat.websocket.utils.ChannelContextUtils;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component("messageHandler")
public class MessageHandler {

    private static final Logger log = LoggerFactory.getLogger(MessageHandler.class);

    private static final String MESSAGE_TOPIC = "message.topic";

    @Resource
    private RedissonClient redisson;

    @Resource
    private ChannelContextUtils channelContextUtils;

    @PostConstruct
    public void listenMessage() {
        RTopic rTopic = redisson.getTopic(MESSAGE_TOPIC);
        rTopic.addListener(MessageSendDTO.class, (MessageSendDTO, messageSendDTO) -> {
            log.info("收到广播消息：{}", JSON.toJSONString(messageSendDTO));
            channelContextUtils.sendMessage(messageSendDTO);
        });
    }

    public void sendMessage(MessageSendDTO messageSendDTO) {
        RTopic rTopic = redisson.getTopic(MESSAGE_TOPIC);
        rTopic.publish(messageSendDTO);
    }
}
